import dayjs from "dayjs";

export default {
  data() {
    return {
      dateValue: [],
      // 年
      years: [],
      // 月
      months: ["01", "02", "03", "04", "05", "06", "07", "08", "09", 10, 11, 12],
      // 天
      days: [],
      // 时
      hours: ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"],
      // 分
      minutes: ["00", "15", "30", "45"],
      indicatorStyle: `height: 40px;`,
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.init();
      }
    }
  },
  methods: {
    bindChange(e) {
      const val = e.detail.value;
      this.dateValue = val;
      // 重新获取天数
      this.days = this.setDays();
    },
    init() {
      let date = ""
      if (this.value) {
        date = dayjs(this.value).format("YYYY-MM-DD-HH-mm");
      } else {
        date = dayjs().format("YYYY-MM-DD-HH-mm");
      }
      const d = date.split("-");

      // 获取年份
      this.getYears();

      // 获取接近分钟
      const mKey = this.getMinute(parseInt(d[4] - 1));
      console.log(mKey, "mKey分钟位置");

      this.dateValue = [this.minYear - 1, parseInt(d[1] - 1), parseInt(d[2] - 1), parseInt(d[3]), mKey];

      // 设置天数
      this.days = this.setDays();
    },
    // 确定
    confirm() {
      this.getTime();
      this.$emit("update:visible", false);
      this.$emit("confirm");
    },
    // 取消
    cancel() {
      this.$emit("update:visible", false);
      this.$emit("cancel");
    },
    // 获取当前时间
    getTime() {
      // 年
      const year = this.years[this.dateValue[0]];
      // 月
      const month = this.months[this.dateValue[1]];
      // 日
      const day = this.days[this.dateValue[2]];
      // 时
      const hour = this.hours[this.dateValue[3]];
      // 分
      const minute = this.minutes[this.dateValue[4]];

      let str = `${year}-${month}-${day}`;
      if (this.type === "datetime") {
        str += ` ${hour}:${minute}`;
      }

      this.$emit("input", str);
    },
    // 设置时
    setDays() {
      const year = this.years[this.dateValue[0]];
      const month = this.months[this.dateValue[1]];
      const days = dayjs(`${year}-${month}`).daysInMonth();
      const s = [];
      for (let i = 1; i <= days; i++) {
        s.push(i < 10 ? "0" + i : i + "");
      }
      return s;
    },
    // 获取分
    getMinute(m) {
      const minte = m;
      if (m <= 8 || m > 53) {
        return 0;
      } else if (m > 8 && m <= 23) {
        return 1;
      } else if (m > 23 && m <= 37) {
        return 2;
      } else if (m > 37 && m <= 53) {
        return 3;
      }

      return minte;
    },
    // 获取年
    getYears() {
      // 当前年
      const presentYears = parseInt(dayjs().format("YYYY"));
      const years = [];
      for (let i = 0; i < this.minYear; i++) {
        years.unshift(presentYears - i);
      }
      this.years = years;
    }
  }
};
